import AppFooter from "@/components/layout/AppFooter";
import HomeBanner from "./components/HomeBanner";
import styled from "styled-components";
import { Col, Row } from "antd";
import AuthorInfo from "./components/AuthorInfo";
import Announcement from "./components/Announcement";
import WebsiteInfo from "./components/WebsiteInfo";
import TalkingCarousel from "./components/TalkingCarousel";
import { useEffect, useRef, useState } from "react";
import { api } from "@/api";
import { useGetState } from "@/hooks";
import { marked } from "marked";
import ArticleCard from "./components/ArticleCard";

const Styled = styled.div`
  width: 100%;
  height: 100%;
  .home {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .home-content {
    padding-left: 3.75rem;
    padding-right: 3.75rem;
    max-width: 307.5rem;
    margin-bottom: 10rem;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
  }
  .author-info {
    position: sticky;
    top: 5rem;
  }
`;

const Home = () => {
  const loadingBox = useRef();
  const [articleList, setArticleList, getArticleList] = useGetState([]);
  const [loading, setLoading] = useState(false);
  // 无限加载文章
  const [params, setParams, getParams] = useGetState({
    page_size: 5,
    page_num: 1,
  }); // 列表加载参数
  const getArticlesInfinite = async () => {
    let n_params = getParams();

    if (!loading) {
      try {
        const res = await api.getArticles(n_params);
        //新旧数据进行合并
        let newList = articleList;
        newList.push(...res.data);
        setArticleList(newList);
        getArticleList().forEach((e) => {
          e.content = filterMdSymbol(e.content);
        });

        setParams({
          ...n_params,
          page_num: n_params.page_num + 1,
        });
        setLoading(false);
      } catch (error) {
        console.log(error);
      }
    }
  };

  //过滤markdown符号转换为html标签
  function filterMdSymbol(mdStr) {
    return marked(mdStr) // 转 HTML
      .replace(/<\/?[^>]*>/g, "") // 正则去除 Html 标签
      .replace(/[|]*\n/, "")
      .replace(/&npsp;/gi, "");
  }

  useEffect(() => {
    const init = async () => {
      try {
        setLoading(true);
        let res = await api.getArticles(params);
        setArticleList(res.data);
        getArticleList().forEach((e) => {
          e.content = filterMdSymbol(e.content);
        });
        setParams({
          ...params,
          page_num: params.page_num + 1,
        });
        setLoading(false);
      } catch (error) {
        console.log("获取文章列表数据失败");
      }
    };
    init();
  }, []);

  useEffect(() => {
    const el = loadingBox.current;
    let observe = new IntersectionObserver(async (entries) => {
      const entry = entries[0];
      if (entry.isIntersecting === true) {
        //代表监事的容器出现在屏幕中需要获取更多数据
        await getArticlesInfinite();
      }
    }, {});
    observe.observe(el);
    return () => {
      observe.unobserve(el);
    };
  }, []);

  return (
    <Styled className="animate-zoom-in ">
      {/* 首页封面图 */}
      <HomeBanner />
      {/* 内容 */}
      <div className="home">
        <div className="home-content" style={{ marginTop: "calc(100vh+30px)" }}>
          <Row gutter={12} style={{ marginTop: "5rem" }}>
            <Col xl={17} xs={24}>
              {/* 说说轮播 */}
              <TalkingCarousel />
              {/* 文章列表 */}
              {articleList.map((item, idx) => {
                return <ArticleCard key={item.id} idx={idx} article={item} />;
              })}
              {/* 无限滚动 */}
              <div
                ref={loadingBox}
                style={{
                  textAlign: "center",
                  color: "rgba(156,163,175,1)",
                  margin: "5rem 0",
                }}
              >
                没有更多数据啦
              </div>
            </Col>
            {/* 右边作者栏 */}
            <Col xl={4} xs={0}>
              {/* 采用sticky定位 */}
              <div className="author-info">
                {/* 博主信息 */}
                <AuthorInfo />
                {/* 公告 */}
                <Announcement />
                {/* 咨询 */}
                <WebsiteInfo />
              </div>
            </Col>
          </Row>
        </div>
        {/* 底部 */}
        <AppFooter />
      </div>
    </Styled>
  );
};

export default Home;
